<template>
	<view>
		<u-toast ref="uToast" />
		<common :tips='commonTips'></common>
		<u-modal v-model="delModelShow" :mask-close-able="true" :show-cancel-button="true" @confirm="delConfirm"
			:content="delModelContent"></u-modal>
		<u-form :model="info" ref="uForm">
			<u-cell-group>
				<view @click="goToUserInfo()">
					<u-cell-item :title="info.sessionUser.nickname">
						<image class="user-avatar" slot="icon" :src="info.sessionUser.avatar" mode="aspectFill"></image>
					</u-cell-item>
				</view>
				<navigator v-if="info.type == 'single' && info.friend"
					:url="'/pages/pick-user/pick-user?action=create-group&preselection=' + info.sessionUser.id">
					<u-cell-item title="创建群聊" :arrow="false">
						<view class="greate-group-chat" slot="icon">
							<u-icon name="plus"></u-icon>
						</view>
					</u-cell-item>
				</navigator>
			</u-cell-group>

			<view v-if="info.type == 'group'" class="u-m-t-20 fff-bg-item">
				<navigator
					:url="'/pages/center/group_chat_notice?group_id=' + info.sessionUser.id + '&session_id=' + id">
					<u-cell-item title="群公告" :value="info.notice"></u-cell-item>
				</navigator>
				<navigator :url="'/pages/center/group_chat_users?id=' + info.sessionUser.id">
					<u-cell-item title="群聊成员" :value="info.sessionUser.user_count + '人'"></u-cell-item>
				</navigator>
				<view class="group-chat-users">
					<!-- :url="'/pages/center/info?type=user&id=' + item.id" -->
					<navigator v-for="(item,index) in groupChatMember" :key="index" class="chat-user-item">
						<image class="chat-user-avatar" :src="item.avatar"></image>
						<view class="chat-user-nickname">{{item.nickname ? item.nickname:item.nickname_origin}}</view>
					</navigator>
					<view @click="invitation" class="chat-user-item">
						<view class="chat-user-avatar-plus" slot="icon">
							<u-icon name="plus"></u-icon>
						</view>
						<view class="chat-user-nickname">邀请</view>
					</view>
				</view>
			</view>

			<view class="u-m-t-20 form-item">
				<u-form-item label="设为置顶" label-width="160">
					<u-switch slot="right" @change="infoSwitchChange('top')" v-model="info.top"></u-switch>
				</u-form-item>
				<u-form-item v-if="info.type == 'single'" label="常用联系人" label-width="160">
					<u-switch slot="right" @change="infoSwitchChange('top_contacts')"
						v-model="info.top_contacts"></u-switch>
				</u-form-item>
				<u-form-item v-if="info.type == 'group'" label="消息免打扰" label-width="160">
					<u-switch slot="right" @change="infoSwitchChange('block_messages')"
						v-model="info.block_messages"></u-switch>
				</u-form-item>
				<u-form-item v-if="info.type == 'group' && myAdminStatus == 1" label="全部禁言" label-width="160">
					<u-switch slot="right" @change="handleBlockSpeackChange" v-model="blockSpeack"></u-switch>
				</u-form-item>
				<u-form-item v-if="info.type == 'single'" label="屏蔽会话" label-width="160">
					<u-switch slot="right" @change="infoSwitchChange('shield')" v-model="info.shield"></u-switch>
				</u-form-item>

				<u-form-item v-if="info.type == 'group'" label="我的群聊备注" label-width="260">
					<view slot="right">
						<u-input @blur="saveRemark" placeholder="请输入备注" :clearable="false" input-align="right"
							type="text" v-model="info.nickname" :border="false" />
					</view>
				</u-form-item>
			</view>

			<view v-if="info.type == 'single'" @click="friendButton" class="u-m-t-20 fff-bg-item color-red">
				<view class="form-button">{{info.friend ? '删除好友':'加为好友'}}</view>
			</view>
			<view v-if="info.type == 'group'" @click="groupButton('exit')" class="u-m-t-20 fff-bg-item color-red">
				<view class="form-button">{{info.isLeader ? '解散群聊':'退出群聊'}}</view>
			</view>
			<view v-if="info.type == 'group' || info.type == 'single'" @click="report"
				class="u-m-t-20 fff-bg-item color-yellow">
				<view class="form-button">举报</view>
			</view>
			<view v-if="info.type == 'service'" @click="delSession" class="u-m-t-20 fff-bg-item color-red">
				<view class="form-button">移除会话</view>
			</view>
		</u-form>
	</view>
</template>

<script>
	import Config from "@/common/config.js"; // 本地配置数据
	export default {
		data() {
			return {
				id: 0,
				info: {
					sessionUser: {
						nickname: '加载中...'
					}
				},
				groupChatMember: [],
				delModelShow: false,
				delModelContent: '',
				commonTips: '',
				hasWatchedOnce: false,
				myAdminStatus: 0,
				blockSpeack: false, // 默认是否禁言
			}
		},
		watch: {
			groupChatMember: {
				handler(newVal) {
					if (!this.hasWatchedOnce && newVal.length > 0) {
						console.log("我要来了哦");
						this.getGroupUserStatus();
						this.hasWatchedOnce = true; // ✅ 标志触发过
					}
				},
				immediate: true
			}
		},
		onLoad: function(query) {
			
			this.id = query.id ? query.id : 0
			this.ws.pageFun(this.pageDataLoad, this);
		},
		onShow: function() {
			this.hasWatchedOnce = false;
			this.ws.checkNetwork(this)
			if (this.ws.invitationGroupmemberSelected) {
				this.ws.pageFun(res => {
					this.ws.send({
						c: 'Message',
						a: 'invitationGroupmember',
						data: {
							pickuser: this.ws.invitationGroupmemberSelected,
							id: this.info.sessionUser.id
						}
					})
				}, this)
				this.ws.invitationGroupmemberSelected = null
			}

			if (this.ws.pageRefresh.chatSetting) {
				this.ws.pageFun(this.pageDataLoad, this);
				this.ws.pageRefresh.chatSetting = false
			}
			// this.getGroupUserStatus();
		},
		methods: {
			initGroupMuteStatus() {
				console.log(this);
				// if (this.info.type !== 'group' || this.myAdminStatus != 1) return;
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
				this.$u.post(`https://${Config.baseUrl}/api/Group_operate/checkAllMuted?im_tourists_token=${userToken}`, {
					group_id: this.info.chat_id
				}).then(res => {
					if (res.status === 'success') {
						this.blockSpeack = res.data.all_muted === true;
					} else {
						this.blockSpeack = false;
					}
				}).catch(err => {
					console.error('获取禁言状态失败', err);
					this.blockSpeack = false;
				});
			},
			handleBlockSpeackChange(val) {
				console.log(val);
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
				const userId = userinfo.id;
				// console.log(this);
				// console.log(JSON.stringify(this, null, 2)); // 美化输出
				// console.log(JSON.stringify(this.info, null, 2)); // 美化输出
				const groupId = this.info.chat_id;
				const isMuted = val ? 1 : 0;

				if (!groupId) {
					this.$refs.uToast?.show({
						title: '缺少群组信息',
						type: 'error'
					});
					this.blockSpeack = !val; // 回滚 switch 状态
					return;
				}

				this.$u.post(
					`https://${Config.baseUrl}/api/Group_operate/setGroupMute?im_tourists_token=${userToken}`, {
						group_id: groupId,
						user_id: userId,
						is_muted: isMuted
					}
				).then(res => {
					if (res.status === 'success') {
						this.$refs.uToast?.show({
							title: res.message,
							type: 'success'
						});
					} else {
						this.$refs.uToast?.show({
							title: res.message || '操作失败',
							type: 'error'
						});
						this.blockSpeack = !val; // 回滚
					}
				}).catch(err => {
					console.error("设置禁言失败", err);
					this.$refs.uToast?.show({
						title: '网络异常',
						type: 'error'
					});
					this.blockSpeack = !val; // 回滚
				});
			},
			getGroupUserStatus() {
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
				const used_id = userinfo.id;
				console.log(JSON.stringify(this.groupChatMember, null, 2));
				console.log(this.id);
				this.$u.post(
					`https://${Config.baseUrl}/api/Group_operate/getGroupUsersBySessionId?im_tourists_token=${userToken}`, {
						session_id: this.id
					}).then(res => {
					if (res.status === 'success') {
						const statusList = res.data;
						const statusMap = {};
						statusList.forEach(item => {
							statusMap[item.user_id] = item;
						});

						this.groupChatMember = this.groupChatMember.map((user, index) => {
							// if (index === 0) {
							// user.is_admin = 1;
							// } else if (statusMap[user.id]) {
							user.is_admin = statusMap[user.id].is_admin;
							user.is_muted = statusMap[user.id].is_muted;
							// }

							// ✅ 单独提取当前用户的 is_admin 值
							console.log(user.id);
							console.log(used_id);

							if (user.id === used_id) {
								console.log("aaaaaa")
								this.myAdminStatus = user.is_admin;
							}
							// console.log(this.myAdminStatus);
							return user;
						});

						console.log('当前用户是否是管理员：', this.myAdminStatus);
						console.log(JSON.stringify(this.groupChatMember, null, 2));
						this.initGroupMuteStatus(); // 加上这个
						// 如果你需要存下来可以这样：
						// this.commonTips = this.myAdminStatus ? '你是管理员' : '你不是管理员';
					} else {
						this.$refs.uToast?.show({
							title: res.message || '获取群成员状态失败',
							type: 'error'
						});
					}
				}).catch(err => {
					console.error("获取群成员状态失败", err);
					this.$refs.uToast?.show({
						title: '网络异常',
						type: 'error'
					});
				});
			},

			pageDataLoad: function() {
				var that = this
				let message = {
					c: 'User',
					a: 'sessionSetting',
					data: {
						'session_id': that.id
					}
				}
				that.ws.send(message);
			},
			friendButton: function() {
				var that = this
				if (that.info.type == 'single' && that.info.friend) {
					that.delContact('user')
				} else {
					uni.navigateTo({
						url: '/pages/search/add-contact?id=' + that.info.sessionUser.id + '&type=user'
					})
				}
			},
			groupButton: function(type) {
				if (type == 'exit') {
					this.delContact('group')
				}
			},
			delContact: function(type) {
				if (type == 'user') {
					this.delModelContent = '你确定要删除此好友吗？';
				} else if (type == 'group') {
					if (this.info.isLeader) {
						this.delModelContent = '你确定要解散群聊吗？';
					} else {
						this.delModelContent = '你确定要退出群聊吗？';
					}
				}
				this.delModelShow = true
			},
			delConfirm: function() {
				var that = this
				if (that.info.type == 'service') {
					// 移除会话
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								action: "session-remove",
								id: that.info.id,
								source: 'uni-app'
							}
						});
					}, that)
					return;
				}
				that.ws.pageFun(function() {
					let message = {
						c: 'User',
						a: 'delContact',
						data: {
							'id': that.info.sessionUser.id,
							'type': (that.info.type == 'single') ? 'user' : 'group'
						}
					}
					that.ws.send(message);
					that.ws.showMsgCallback = function() {
						that.ws.pageRefresh.message = true
						that.ws.pageRefresh.addressList = true
						setTimeout(function() {
							uni.switchTab({
								url: '/pages/message/message'
							})
						}, 2000)
					}
				}, that)
			},
			report: function() {
				uni.navigateTo({
					url: '/pages/center/report?title=举报&type=user&id=' + this.id
				})
			},
			infoSwitchChange: function(name) {
				var that = this
				if (name == 'top') {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								id: that.id,
								action: 'session-top',
								source: 'uni-app'
							}
						})
					}, that)
				} else if (name == 'top_contacts') {
					that.ws.pageFun(function() {
						var new_group = 'common'
						if (that.info.sessionUser.group == 'common') {
							new_group = 'all_friends'
						}
						that.ws.send({
							c: 'User',
							a: 'updateFriendInfo',
							data: {
								id: that.info.sessionUser.id,
								new_group: new_group,
								method: 'update_group',
								source: 'uni-app'
							}
						});
						that.info.top_contacts = (new_group == 'common') ? true : false;
					}, that)
				} else if (name == 'shield') {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'shieldSession',
							data: {
								session_id: that.id,
								method: that.info.shield ? 'shield' : 'relieve'
							}
						})
					}, that)
				} else if (name == 'block_messages') {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								id: that.id,
								action: 'session-block-groupmessage',
								source: 'uni-app'
							}
						})
					}, that)
				}
			},
			saveRemark: function(val) {
				var that = this
				if (val != that.info.oldnickname) {
					that.ws.send({
						c: 'Message',
						a: 'groupChatMember',
						data: {
							id: that.info.sessionUser.id,
							new_nickname: val,
							method: 'save-groupmember-nickname'
						}
					});
				}
			},
			invitation: function() {
				uni.navigateTo({
					url: '/pages/pick-user/pick-user?action=invitation-groupmember'
				})
			},
			goToUserInfo: function() {
				var url = '/pages/center/info?type=' + (this.info.type == 'single' ? 'user' : this.info.type) +
					'&id=' + this.info.sessionUser.id
				uni.navigateTo({
					url: url
				})
			},
			delSession: function() {
				this.delModelContent = '你确定要移除此会话吗？';
				this.delModelShow = true
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: $--bg-color;
	}

	.user-avatar {
		height: 100rpx;
		width: 100rpx;
		margin-right: 20rpx;
		border-radius: 16rpx;
	}

	.form-item {
		background: $--white;
		padding: 0 6vw;
	}

	.fff-bg-item {
		background: $--white;
	}

	.form-button {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}

	.greate-group-chat {
		display: flex;
		align-items: center;
		justify-content: center;
		background: $--grey;
		height: 100rpx;
		width: 100rpx;
		margin-right: 20rpx;
		border-radius: 16rpx;
	}

	.color-blue {
		color: $--blue;
	}

	.color-red {
		color: $--red;
	}

	.color-yellow {
		color: $u-type-warning;
	}

	.group-chat-users {
		padding-left: 20rpx;
		padding-bottom: 10rpx;
		display: flex;
		flex-wrap: wrap;
		width: 100vw;
	}

	.chat-user-item {
		width: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.chat-user-item .chat-user-avatar {
		height: 100rpx;
		width: 100rpx;
		border-radius: 16rpx;
	}

	.chat-user-avatar-plus {
		height: 100rpx;
		width: 100rpx;
		border-radius: 16rpx;
		background: #F4F5F6;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.chat-user-nickname {
		font-size: 26rpx;
		padding-top: 10rpx;
		width: 100rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		text-align: center;
	}
</style>